export const baseURL = 'https://api.vika.cn'
// 请求拦截
const apiHandle = async (method, url, data, headers) => {

	headers = Object.assign({
		'Content-Type': 'application/json; charset=utf-8', //注意格式
		'Accept': 'application/json',
	}, headers);
	let token = 'uskzGl2IEaC6VMsDYjSJw0R';
	if (token) {
		headers.Authorization = 'Bearer ' + token;
		headers['Content-Type']= 'application/json'
	}
	return new Promise((response, reject) => {
		console.log(baseURL + url)
		uni.request({
			url: baseURL + url,
			data,
			header: headers,
			method,
			timeout: 60000,
			success: (res) => {
				const { data, statusCode } = res;
				console.log('statusCode', statusCode)
				if (statusCode == 200) {
					response(data);
				} else {
					uni.showToast({
						icon: 'none',
						title: '服务器错误，请稍后重试'
					})
					// uni.showModal({
					// 	title: '提示',
					// 	content: '服务器错误，请稍后重试'
					// })
					response(data);
				}
			},
			fail: (err) => {
				console.log('提示err', err);
				response(err);
			},
		});
	});
};
// 方法导出 和 返回拦截
export const apiGet = async (url, data = {}, headers = {}) => {
	const res = await apiHandle('GET', url, data, headers);
	console.log(`请求: ${url}`)
	console.log(`请求: ${url}  返回值:`, res)
	const { data: body, code, message } = res;
	if (code != 200) {
		uni.showToast({
			icon: 'none',
			title: message
		})
		return false
	}
	if (body.records && Array.isArray(body.records)) {
		body.records = body.records.map(item => {
			return item.fields
		})
	}
	
	return body;
};

export const apiPost = async (url, data = {}, headers = {}) => {
	const res = await apiHandle('POST', url, data, headers);
	console.log(`请求: ${url}  参数:`, data)
	console.log(`请求: ${url}  返回值:`, res)
	const { data: body, code, msg } = res;
	if (code != 1) {
		uni.showToast({
			icon: 'none',
			title: msg
		})
		return false
	}
	return body;
};
